/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package by.vdl.websort.server.dao.rowmapper;

import by.vdl.websort.server.entity.CategoryDTO;
import by.vdl.websort.server.entity.ItemDTO;
import by.vdl.websort.server.entity.StudyDTO;
import by.vdl.websort.server.entity.contextmodels.StudyUnsortedModel;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 *
 * @author zeor
 */
public class UnsortedStudyResultSetExtractor implements ResultSetExtractor<StudyUnsortedModel>{

    public StudyUnsortedModel extractData(ResultSet rs) throws SQLException, DataAccessException {
        StudyUnsortedModel studyUnsortedModel = new StudyUnsortedModel();
        boolean isFirstTime = true;
        StudyDTO studyDTO = null;
        while(rs.next()){
            if(isFirstTime){
                studyDTO = new StudyDTO();
                studyDTO.setId(rs.getLong("studyId"));
                studyDTO.setName(rs.getString("studyName"));
                studyDTO.setUserId(rs.getLong("userId"));
                studyUnsortedModel.setStudy(studyDTO);
                isFirstTime = false;
            }
            CategoryDTO categoryDTO = new CategoryDTO();
            categoryDTO.setId(rs.getLong("categoryId"));
            categoryDTO.setName(rs.getString("categoryName"));
            categoryDTO.setStudyId(studyDTO.getId());
            
            if(!studyUnsortedModel.getCategories().contains(categoryDTO))
                studyUnsortedModel.getCategories().add(categoryDTO);
            
            ItemDTO itemDTO = new ItemDTO();
            itemDTO.setId(rs.getLong("itemId"));
            itemDTO.setName(rs.getString("itemName"));
            itemDTO.setStudyId(studyDTO.getId());
            
            if(!studyUnsortedModel.getItems().contains(itemDTO))
                studyUnsortedModel.getItems().add(itemDTO); 
        }
        return studyUnsortedModel;
    }
    
}
